﻿using MES.Desktop.Common;
using MES.Desktop.IService;
using MES.Desktop.SystemModule.Models;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MES.Desktop.SystemModule.ViewModels
{
    public class MenuViewModel : PageViewModelBase
    {
        public ObservableCollection<MenuModel> Menus { get; set; } =
            new ObservableCollection<MenuModel>();

        List<Entities.MenuEntity> origMenus;

        private bool isSyncSelect;
        private bool _isSelectAll;

        public bool IsSelectAll
        {
            get { return _isSelectAll; }
            set
            {
                SetProperty<bool>(ref _isSelectAll, value);

                if (isSyncSelect) return;
                isSyncSelect = true;

                foreach (var menu in Menus)
                    menu.IsSelected = value;

                isSyncSelect = false;
            }
        }

        IMenuService _menuService;
        IEventAggregator _eventAggregator;
        IDialogService _dialogService;
        IFuncService _funcService;
        public MenuViewModel(IRegionManager regionManager,
            IMenuService menuService,
            IEventAggregator eventAggregator,
            IDialogService dialogService,
            IFuncService funcService)
            : base(regionManager)
        {
            this.PageTitle = "系统菜单管理";

            _menuService = menuService;
            _eventAggregator = eventAggregator;
            _dialogService = dialogService;
            _funcService = funcService;
            this.Refresh();
        }

        public override void Refresh()
        {
            Menus.Clear();

            _eventAggregator.GetEvent<LoadingEvent>()
                .Publish("正在加载文件....");

            Task.Run(() =>
            {
                try
                {
                    origMenus = _menuService.GetAllMenus(SearchKey).ToList();
                    this.FillMenus(Menus, null, origMenus);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示");
                }
                finally
                {
                    _eventAggregator.GetEvent<LoadingEvent>()
                        .Publish("");
                }
            });
        }

        public void FillMenus(ObservableCollection<MenuModel> menus,
            MenuModel parent, List<Entities.MenuEntity> origMenus, bool expandedNode = true)
        {
            var sub = origMenus.Where(m => m.MenuId != "0" &&
                    m.ParentId == (parent == null ? "-1" : parent.MenuId)).ToList();

            if (sub.Count() > 0)
            {
                foreach (Entities.MenuEntity item in sub)
                {
                    string icon = "";
                    if (!string.IsNullOrEmpty(item.MenuIcon))
                        icon = ((char)int.Parse(item.MenuIcon, NumberStyles.HexNumber))
                                    .ToString();
                    MenuModel model = new MenuModel
                    {
                        MenuId = item.MenuId,
                        MenuHeader = item.MenuHeader,
                        MenuIcon = icon,
                        TargetView = item.TargetView,
                        ParentId = (parent == null ? "-1" : parent.MenuId),
                        IsExpanded = expandedNode,
                        Parent = parent,
                        FuncIds = item.Funcs,
                        FuncNames= item.FuncNames,
                    };




                    model.PropertyChanged += (se, ev) =>
                    {
                        if (isSyncSelect) return;
                        isSyncSelect = true;

                        if (ev.PropertyName == "IsSelected")
                            this.IsSelectAll = Menus.All(f => f.IsSelected);

                        isSyncSelect = false;
                    };
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        menus.Add(model);
                    });

                    FillMenus(model.Children, model, origMenus);
                }

                if (menus.Count > 0)
                {
                    menus[menus.Count - 1].IsLastChild = true;
                }
            }
        }


        public override void DoModify(object obj)
        {
            DialogParameters ps = new DialogParameters();
            ps.Add("model", obj);


            // 获取所有一级菜单
            var prents = origMenus.Where(m => m.ParentId == "-1" && m.MenuId != "0")
                .ToList();
            ps.Add("parents", prents);

            _dialogService.ShowDialog("ModifyMenuView", ps, result =>
            {
                // 判断子窗口的返回状态，如果OK，刷新当前页面，否则不管
                if (result.Result == ButtonResult.OK)
                {
                    this.Refresh();

                    // 重新启动系统
                }
            });

        }

        public override void DoBatchDelete()
        {
            var mb_result = MessageBox.Show("是否确认删除当前记录？", "提示", MessageBoxButton.YesNo);
            if (mb_result != MessageBoxResult.Yes) return;

            _eventAggregator.GetEvent<LoadingEvent>()
               .Publish("正在删除菜单....");

            List<string> ids = new List<string>();
            foreach (var model in Menus)
            {
                if (model.IsSelected) ids.Add(model.MenuId);
                foreach (var item in model.Children)
                {
                    if (item.IsSelected) ids.Add(item.MenuId);
                }
            }
            Task.Run(() =>
            {
                try
                {
                    int count = _menuService.DeleteMenus(ids.ToArray());
                    if (count == 0)
                    {
                        throw new Exception("删除记录失败");
                    }
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        this.Refresh();
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示");
                }
                finally
                {
                    _eventAggregator.GetEvent<LoadingEvent>()
                        .Publish("");
                }
            });
        }

        public override void DoDelete(object obj)
        {
            var mb_result = MessageBox.Show("是否确认删除当前记录？", "提示", MessageBoxButton.YesNo);
            if (mb_result != MessageBoxResult.Yes) return;

            _eventAggregator.GetEvent<LoadingEvent>()
                .Publish("正在删除菜单....");

            string id = (obj as MenuModel).MenuId;
            Task.Run(() =>
            {
                try
                {
                    int count = _menuService.DeleteMenu(id);
                    if (count == 0)
                    {
                        throw new Exception("删除记录失败");
                    }
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        this.Refresh();
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示");
                }
                finally
                {
                    _eventAggregator.GetEvent<LoadingEvent>()
                        .Publish("");
                }
            });
        }
    }
}
